{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 模型，提示和输出解释器\n",
    "\n",
    "\n",
    "**目录**\n",
    "* 获取你的OpenAI API Key\n",
    "* 直接调用OpenAI的API\n",
    "* 通过LangChain进行的API调用：\n",
    "  * 提示（Prompts）\n",
    "  * [模型（Models)](#model)\n",
    "  * 输出解析器（Output parsers）\n",
    "  "
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "## 获取你的OpenAI API Key\n",
    "\n",
    "登陆[OpenAI账户获取你的API Key](https://platform.openai.com/account/api-keys) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 下载需要的包python-dotenv和openai\n",
    "# 如果你需要查看安装过程日志，可删除 -q \n",
    "!pip install -q python-dotenv\n",
    "!pip install -q openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-14T14:41:51.383899Z",
     "end_time": "2023-06-14T14:41:51.391180Z"
    }
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import openai\n",
    "# 运行此API配置，需要将目录中的.env中api_key替换为自己的\n",
    "from dotenv import load_dotenv, find_dotenv\n",
    "_ = load_dotenv(find_dotenv()) # read local .env file\n",
    "# 导入 OpenAI API_KEY\n",
    "openai.api_key = os.environ['OPENAI_API_KEY']"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Chat API：OpenAI\n",
    "\n",
    "我们先从直接调用OpenAI的API开始。\n",
    "\n",
    "`get_completion`函数是基于`openai`的封装函数，对于给定提示（prompt）输出相应的回答。其包含两个参数\n",
    "   \n",
    "   - `prompt` 必需输入参数。 你给模型的提示，可以是一个问题，可以是你需要模型帮助你做的事（改变文本写作风格，翻译，回复消息等等）。\n",
    "   - `model` 非必需输入参数。默认使用gpt-3.5-turbo。你也可以选择其他模型。\n",
    "   \n",
    "这里的提示对应我们给chatgpt的问题，函数给出的输出则对应chatpgt给我们的答案。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-14T14:42:10.039293Z",
     "end_time": "2023-06-14T14:42:10.048045Z"
    }
   },
   "outputs": [],
   "source": [
    "def get_completion(prompt, model=\"gpt-3.5-turbo\"):\n",
    "    \n",
    "    messages = [{\"role\": \"user\", \"content\": prompt}]\n",
    "    \n",
    "    response = openai.ChatCompletion.create(\n",
    "        model=model,\n",
    "        messages=messages,\n",
    "        temperature=0, \n",
    "    )\n",
    "    return response.choices[0].message[\"content\"]"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "### 一个简单的例子\n",
    "\n",
    "我们来一个简单的例子 - 分别用中英文问问模型\n",
    "\n",
    "- 中文提示(Prompt in Chinese)： `1+1是什么？`\n",
    "- 英文提示(Prompt in English)： `What is 1+1?`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2023-06-13T17:59:36.173723Z",
     "end_time": "2023-06-13T17:59:43.133034Z"
    }
   },
   "outputs": [
    {
     "ename": "AuthenticationError",
     "evalue": "<empty message>",
     "output_type": "error",
     "traceback": [
      "\u001B[0;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[0;31mAuthenticationError\u001B[0m                       Traceback (most recent call last)",
      "Cell \u001B[0;32mIn[65], line 1\u001B[0m\n\u001B[0;32m----> 1\u001B[0m \u001B[43mget_completion\u001B[49m\u001B[43m(\u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43m1+1是什么？\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m)\u001B[49m\n",
      "Cell \u001B[0;32mIn[64], line 5\u001B[0m, in \u001B[0;36mget_completion\u001B[0;34m(prompt, model)\u001B[0m\n\u001B[1;32m      1\u001B[0m \u001B[38;5;28;01mdef\u001B[39;00m \u001B[38;5;21mget_completion\u001B[39m(prompt, model\u001B[38;5;241m=\u001B[39m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mgpt-3.5-turbo\u001B[39m\u001B[38;5;124m\"\u001B[39m):\n\u001B[1;32m      3\u001B[0m     messages \u001B[38;5;241m=\u001B[39m [{\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mrole\u001B[39m\u001B[38;5;124m\"\u001B[39m: \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124muser\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mcontent\u001B[39m\u001B[38;5;124m\"\u001B[39m: prompt}]\n\u001B[0;32m----> 5\u001B[0m     response \u001B[38;5;241m=\u001B[39m \u001B[43mopenai\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mChatCompletion\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mcreate\u001B[49m\u001B[43m(\u001B[49m\n\u001B[1;32m      6\u001B[0m \u001B[43m        \u001B[49m\u001B[43mmodel\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43mmodel\u001B[49m\u001B[43m,\u001B[49m\n\u001B[1;32m      7\u001B[0m \u001B[43m        \u001B[49m\u001B[43mmessages\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43mmessages\u001B[49m\u001B[43m,\u001B[49m\n\u001B[1;32m      8\u001B[0m \u001B[43m        \u001B[49m\u001B[43mtemperature\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[38;5;241;43m0\u001B[39;49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\n\u001B[1;32m      9\u001B[0m \u001B[43m    \u001B[49m\u001B[43m)\u001B[49m\n\u001B[1;32m     10\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m response\u001B[38;5;241m.\u001B[39mchoices[\u001B[38;5;241m0\u001B[39m]\u001B[38;5;241m.\u001B[39mmessage[\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mcontent\u001B[39m\u001B[38;5;124m\"\u001B[39m]\n",
      "File \u001B[0;32m/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/openai/api_resources/chat_completion.py:25\u001B[0m, in \u001B[0;36mChatCompletion.create\u001B[0;34m(cls, *args, **kwargs)\u001B[0m\n\u001B[1;32m     23\u001B[0m \u001B[38;5;28;01mwhile\u001B[39;00m \u001B[38;5;28;01mTrue\u001B[39;00m:\n\u001B[1;32m     24\u001B[0m     \u001B[38;5;28;01mtry\u001B[39;00m:\n\u001B[0;32m---> 25\u001B[0m         \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28;43msuper\u001B[39;49m\u001B[43m(\u001B[49m\u001B[43m)\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mcreate\u001B[49m\u001B[43m(\u001B[49m\u001B[38;5;241;43m*\u001B[39;49m\u001B[43margs\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;241;43m*\u001B[39;49m\u001B[38;5;241;43m*\u001B[39;49m\u001B[43mkwargs\u001B[49m\u001B[43m)\u001B[49m\n\u001B[1;32m     26\u001B[0m     \u001B[38;5;28;01mexcept\u001B[39;00m TryAgain \u001B[38;5;28;01mas\u001B[39;00m e:\n\u001B[1;32m     27\u001B[0m         \u001B[38;5;28;01mif\u001B[39;00m timeout \u001B[38;5;129;01mis\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m \u001B[38;5;129;01mand\u001B[39;00m time\u001B[38;5;241m.\u001B[39mtime() \u001B[38;5;241m>\u001B[39m start \u001B[38;5;241m+\u001B[39m timeout:\n",
      "File \u001B[0;32m/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/openai/api_resources/abstract/engine_api_resource.py:153\u001B[0m, in \u001B[0;36mEngineAPIResource.create\u001B[0;34m(cls, api_key, api_base, api_type, request_id, api_version, organization, **params)\u001B[0m\n\u001B[1;32m    127\u001B[0m \u001B[38;5;129m@classmethod\u001B[39m\n\u001B[1;32m    128\u001B[0m \u001B[38;5;28;01mdef\u001B[39;00m \u001B[38;5;21mcreate\u001B[39m(\n\u001B[1;32m    129\u001B[0m     \u001B[38;5;28mcls\u001B[39m,\n\u001B[0;32m   (...)\u001B[0m\n\u001B[1;32m    136\u001B[0m     \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mparams,\n\u001B[1;32m    137\u001B[0m ):\n\u001B[1;32m    138\u001B[0m     (\n\u001B[1;32m    139\u001B[0m         deployment_id,\n\u001B[1;32m    140\u001B[0m         engine,\n\u001B[0;32m   (...)\u001B[0m\n\u001B[1;32m    150\u001B[0m         api_key, api_base, api_type, api_version, organization, \u001B[38;5;241m*\u001B[39m\u001B[38;5;241m*\u001B[39mparams\n\u001B[1;32m    151\u001B[0m     )\n\u001B[0;32m--> 153\u001B[0m     response, _, api_key \u001B[38;5;241m=\u001B[39m \u001B[43mrequestor\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mrequest\u001B[49m\u001B[43m(\u001B[49m\n\u001B[1;32m    154\u001B[0m \u001B[43m        \u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43mpost\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m,\u001B[49m\n\u001B[1;32m    155\u001B[0m \u001B[43m        \u001B[49m\u001B[43murl\u001B[49m\u001B[43m,\u001B[49m\n\u001B[1;32m    156\u001B[0m \u001B[43m        \u001B[49m\u001B[43mparams\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43mparams\u001B[49m\u001B[43m,\u001B[49m\n\u001B[1;32m    157\u001B[0m \u001B[43m        \u001B[49m\u001B[43mheaders\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43mheaders\u001B[49m\u001B[43m,\u001B[49m\n\u001B[1;32m    158\u001B[0m \u001B[43m        \u001B[49m\u001B[43mstream\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43mstream\u001B[49m\u001B[43m,\u001B[49m\n\u001B[1;32m    159\u001B[0m \u001B[43m        \u001B[49m\u001B[43mrequest_id\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43mrequest_id\u001B[49m\u001B[43m,\u001B[49m\n\u001B[1;32m    160\u001B[0m \u001B[43m        \u001B[49m\u001B[43mrequest_timeout\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43mrequest_timeout\u001B[49m\u001B[43m,\u001B[49m\n\u001B[1;32m    161\u001B[0m \u001B[43m    \u001B[49m\u001B[43m)\u001B[49m\n\u001B[1;32m    163\u001B[0m     \u001B[38;5;28;01mif\u001B[39;00m stream:\n\u001B[1;32m    164\u001B[0m         \u001B[38;5;66;03m# must be an iterator\u001B[39;00m\n\u001B[1;32m    165\u001B[0m         \u001B[38;5;28;01massert\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m \u001B[38;5;28misinstance\u001B[39m(response, OpenAIResponse)\n",
      "File \u001B[0;32m/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/openai/api_requestor.py:226\u001B[0m, in \u001B[0;36mAPIRequestor.request\u001B[0;34m(self, method, url, params, headers, files, stream, request_id, request_timeout)\u001B[0m\n\u001B[1;32m    205\u001B[0m \u001B[38;5;28;01mdef\u001B[39;00m \u001B[38;5;21mrequest\u001B[39m(\n\u001B[1;32m    206\u001B[0m     \u001B[38;5;28mself\u001B[39m,\n\u001B[1;32m    207\u001B[0m     method,\n\u001B[0;32m   (...)\u001B[0m\n\u001B[1;32m    214\u001B[0m     request_timeout: Optional[Union[\u001B[38;5;28mfloat\u001B[39m, Tuple[\u001B[38;5;28mfloat\u001B[39m, \u001B[38;5;28mfloat\u001B[39m]]] \u001B[38;5;241m=\u001B[39m \u001B[38;5;28;01mNone\u001B[39;00m,\n\u001B[1;32m    215\u001B[0m ) \u001B[38;5;241m-\u001B[39m\u001B[38;5;241m>\u001B[39m Tuple[Union[OpenAIResponse, Iterator[OpenAIResponse]], \u001B[38;5;28mbool\u001B[39m, \u001B[38;5;28mstr\u001B[39m]:\n\u001B[1;32m    216\u001B[0m     result \u001B[38;5;241m=\u001B[39m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mrequest_raw(\n\u001B[1;32m    217\u001B[0m         method\u001B[38;5;241m.\u001B[39mlower(),\n\u001B[1;32m    218\u001B[0m         url,\n\u001B[0;32m   (...)\u001B[0m\n\u001B[1;32m    224\u001B[0m         request_timeout\u001B[38;5;241m=\u001B[39mrequest_timeout,\n\u001B[1;32m    225\u001B[0m     )\n\u001B[0;32m--> 226\u001B[0m     resp, got_stream \u001B[38;5;241m=\u001B[39m \u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43m_interpret_response\u001B[49m\u001B[43m(\u001B[49m\u001B[43mresult\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mstream\u001B[49m\u001B[43m)\u001B[49m\n\u001B[1;32m    227\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m resp, got_stream, \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mapi_key\n",
      "File \u001B[0;32m/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/openai/api_requestor.py:620\u001B[0m, in \u001B[0;36mAPIRequestor._interpret_response\u001B[0;34m(self, result, stream)\u001B[0m\n\u001B[1;32m    612\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m (\n\u001B[1;32m    613\u001B[0m         \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39m_interpret_response_line(\n\u001B[1;32m    614\u001B[0m             line, result\u001B[38;5;241m.\u001B[39mstatus_code, result\u001B[38;5;241m.\u001B[39mheaders, stream\u001B[38;5;241m=\u001B[39m\u001B[38;5;28;01mTrue\u001B[39;00m\n\u001B[1;32m    615\u001B[0m         )\n\u001B[1;32m    616\u001B[0m         \u001B[38;5;28;01mfor\u001B[39;00m line \u001B[38;5;129;01min\u001B[39;00m parse_stream(result\u001B[38;5;241m.\u001B[39miter_lines())\n\u001B[1;32m    617\u001B[0m     ), \u001B[38;5;28;01mTrue\u001B[39;00m\n\u001B[1;32m    618\u001B[0m \u001B[38;5;28;01melse\u001B[39;00m:\n\u001B[1;32m    619\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m (\n\u001B[0;32m--> 620\u001B[0m         \u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43m_interpret_response_line\u001B[49m\u001B[43m(\u001B[49m\n\u001B[1;32m    621\u001B[0m \u001B[43m            \u001B[49m\u001B[43mresult\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mcontent\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mdecode\u001B[49m\u001B[43m(\u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43mutf-8\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m)\u001B[49m\u001B[43m,\u001B[49m\n\u001B[1;32m    622\u001B[0m \u001B[43m            \u001B[49m\u001B[43mresult\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mstatus_code\u001B[49m\u001B[43m,\u001B[49m\n\u001B[1;32m    623\u001B[0m \u001B[43m            \u001B[49m\u001B[43mresult\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mheaders\u001B[49m\u001B[43m,\u001B[49m\n\u001B[1;32m    624\u001B[0m \u001B[43m            \u001B[49m\u001B[43mstream\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[38;5;28;43;01mFalse\u001B[39;49;00m\u001B[43m,\u001B[49m\n\u001B[1;32m    625\u001B[0m \u001B[43m        \u001B[49m\u001B[43m)\u001B[49m,\n\u001B[1;32m    626\u001B[0m         \u001B[38;5;28;01mFalse\u001B[39;00m,\n\u001B[1;32m    627\u001B[0m     )\n",
      "File \u001B[0;32m/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/openai/api_requestor.py:683\u001B[0m, in \u001B[0;36mAPIRequestor._interpret_response_line\u001B[0;34m(self, rbody, rcode, rheaders, stream)\u001B[0m\n\u001B[1;32m    681\u001B[0m stream_error \u001B[38;5;241m=\u001B[39m stream \u001B[38;5;129;01mand\u001B[39;00m \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124merror\u001B[39m\u001B[38;5;124m\"\u001B[39m \u001B[38;5;129;01min\u001B[39;00m resp\u001B[38;5;241m.\u001B[39mdata\n\u001B[1;32m    682\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m stream_error \u001B[38;5;129;01mor\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m \u001B[38;5;241m200\u001B[39m \u001B[38;5;241m<\u001B[39m\u001B[38;5;241m=\u001B[39m rcode \u001B[38;5;241m<\u001B[39m \u001B[38;5;241m300\u001B[39m:\n\u001B[0;32m--> 683\u001B[0m     \u001B[38;5;28;01mraise\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mhandle_error_response(\n\u001B[1;32m    684\u001B[0m         rbody, rcode, resp\u001B[38;5;241m.\u001B[39mdata, rheaders, stream_error\u001B[38;5;241m=\u001B[39mstream_error\n\u001B[1;32m    685\u001B[0m     )\n\u001B[1;32m    686\u001B[0m \u001B[38;5;28;01mreturn\u001B[39;00m resp\n",
      "\u001B[0;31mAuthenticationError\u001B[0m: <empty message>"
     ]
    }
   ],
   "source": [
    "get_completion(\"1+1是什么？\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'As an AI language model, I can tell you that the answer to 1+1 is 2.'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "get_completion(\"What is 1+1?\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 复杂一点例子\n",
    "\n",
    "上面的简单例子，模型`gpt-3.5-turbo`对我们的关于1+1是什么的提问给出了回答。\n",
    "\n",
    "现在我们来看一个复杂一点的例子： \n",
    "\n",
    "假设我们是电商公司员工，我们的顾客是一名海盗A，他在我们的网站上买了一个榨汁机用来做奶昔，在制作奶昔的过程中，奶昔的盖子飞了出去，弄得厨房墙上到处都是。于是海盗A给我们的客服中心写来以下邮件：`customer_email`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:00:45.678556Z",
     "end_time": "2023-06-13T18:00:45.689376Z"
    }
   },
   "outputs": [],
   "source": [
    "customer_email = \"\"\"\n",
    "Arrr, I be fuming that me blender lid \\\n",
    "flew off and splattered me kitchen walls \\\n",
    "with smoothie! And to make matters worse,\\\n",
    "the warranty don't cover the cost of \\\n",
    "cleaning up me kitchen. I need yer help \\\n",
    "right now, matey!\n",
    "\"\"\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们的客服人员对于海盗的措辞表达觉得有点难以理解。 现在我们想要实现两个小目标：\n",
    "\n",
    "- 让模型用美式英语的表达方式将海盗的邮件进行翻译，客服人员可以更好理解。*这里海盗的英文表达可以理解为英文的方言，其与美式英语的关系，就如四川话与普通话的关系。\n",
    "- 让模型在翻译是用平和尊重的语气进行表达，客服人员的心情也会更好。\n",
    "\n",
    "根据这两个小目标，定义一下文本表达风格：`style`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:02:24.799482Z",
     "end_time": "2023-06-13T18:02:24.809643Z"
    }
   },
   "outputs": [],
   "source": [
    "# 美式英语 + 平静、尊敬的语调\n",
    "style = \"\"\"American English \\\n",
    "in a calm and respectful tone\n",
    "\"\"\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "下一步需要做的是将`customer_email`和`style`结合起来构造我们的提示:`prompt`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:02:27.421394Z",
     "end_time": "2023-06-13T18:02:27.428061Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Translate the text that is delimited by triple backticks \n",
      "into a style that is American English in a calm and respectful tone\n",
      ".\n",
      "text: ```\n",
      "Arrr, I be fuming that me blender lid flew off and splattered me kitchen walls with smoothie! And to make matters worse,the warranty don't cover the cost of cleaning up me kitchen. I need yer help right now, matey!\n",
      "```\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 要求模型根据给出的语调进行转化\n",
    "prompt = f\"\"\"Translate the text \\\n",
    "that is delimited by triple backticks \n",
    "into a style that is {style}.\n",
    "text: ```{customer_email}```\n",
    "\"\"\"\n",
    "\n",
    "print(prompt)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`prompt` 构造好了，我们可以调用`get_completion`得到我们想要的结果 - 用平和尊重的语气，美式英语表达的海岛邮件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:02:32.096365Z",
     "end_time": "2023-06-13T18:02:34.859751Z"
    }
   },
   "outputs": [],
   "source": [
    "response = get_completion(prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:02:34.861487Z",
     "end_time": "2023-06-13T18:02:34.863536Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": "'I am quite upset that my blender lid came off and caused my smoothie to splatter all over my kitchen walls. Additionally, the warranty does not cover the cost of cleaning up the mess. Would you be able to assist me, please? Thank you kindly.'"
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对比语言风格转换前后，用词更为正式，替换了极端情绪的表达，并表达了感谢。\n",
    "- Arrr, I be fuming（呀，我气的发抖） 换成了 I am quite upset （我有点失望）\n",
    "- And to make matters worse（更糟糕地是），换成了 Additionally(还有)\n",
    "- I need yer help right now, matey!（我需要你的帮助），换成了Would you be able to assist me, please? Thank you kindly.（请问您能帮我吗？非常感谢您的好意）\n",
    "\n",
    "\n",
    "✨ 你可以尝试修改提示，看可以得到什么不一样的结果😉"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Chat API：LangChain\n",
    "\n",
    "在前面一部分，我们通过封装函数`get_completion`直接调用了OpenAI完成了对海岛邮件进行了翻译，得到用平和尊重的语气、美式英语表达的邮件。\n",
    "\n",
    "让我们尝试使用LangChain来实现相同的功能。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 如果你需要查看安装过程日志，可删除 -q \n",
    "# --upgrade 让我们可以安装到最新版本的 langchain\n",
    "!pip install -q --upgrade langchain"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "### 模型<a id='model'></a>\n",
    "\n",
    "从`langchain.chat_models`导入`OpenAI`的对话模型`ChatOpenAI`。 除去OpenAI以外，`langchain.chat_models`还集成了其他对话模型，更多细节可以查看[Langchain官方文档](https://python.langchain.com/en/latest/modules/models/chat/integrations.html)。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:06:09.632279Z",
     "end_time": "2023-06-13T18:06:10.368060Z"
    }
   },
   "outputs": [],
   "source": [
    "from langchain.chat_models import ChatOpenAI"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:06:12.100526Z",
     "end_time": "2023-06-13T18:06:12.123740Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": "ChatOpenAI(lc_kwargs={'temperature': 0.0}, verbose=False, callbacks=None, callback_manager=None, client=<class 'openai.api_resources.chat_completion.ChatCompletion'>, model_name='gpt-3.5-turbo', temperature=0.0, model_kwargs={}, openai_api_key='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', openai_api_base='', openai_organization='', openai_proxy='', request_timeout=None, max_retries=6, streaming=False, n=1, max_tokens=None)"
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 这里我们将参数temperature设置为0.0，从而减少生成答案的随机性。\n",
    "# 如果你想要每次得到不一样的有新意的答案，可以尝试调整该参数。\n",
    "chat = ChatOpenAI(temperature=0.0)\n",
    "chat"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上面的输出显示ChatOpenAI的默认模型为`gpt-3.5-turbo`"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 提示模板\n",
    "\n",
    "在前面的例子中，我们通过[f字符串](https://docs.python.org/zh-cn/3/tutorial/inputoutput.html#tut-f-strings)把Python表达式的值`style`和`customer_email`添加到`prompt`字符串内。\n",
    "\n",
    "```python\n",
    "prompt = f\"\"\"Translate the text \\\n",
    "that is delimited by triple backticks \n",
    "into a style that is {style}.\n",
    "text: ```{customer_email}```\n",
    "\"\"\"\n",
    "```\n",
    "`langchain`提供了接口方便快速的构造和使用提示。现在我们来看看如何使用`langchain`来构造提示。"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 📚 使用LongChain提示模版\n",
    "##### 1️⃣ 构造提示模版字符串\n",
    "我们构造一个提示模版字符串：`template_string`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:40:05.770752Z",
     "end_time": "2023-06-13T18:40:05.773846Z"
    }
   },
   "outputs": [],
   "source": [
    "template_string = \"\"\"Translate the text \\\n",
    "that is delimited by triple backticks \\\n",
    "into a style that is {style}. \\\n",
    "text: ```{text}```\n",
    "\"\"\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 2️⃣ 构造LangChain提示模版\n",
    "我们调用`ChatPromptTemplatee.from_template()`函数将上面的提示模版字符`template_string`转换为提示模版`prompt_template`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:40:08.920834Z",
     "end_time": "2023-06-13T18:40:08.926898Z"
    }
   },
   "outputs": [],
   "source": [
    "# 需要安装最新版的 LangChain\n",
    "from langchain.prompts import ChatPromptTemplate\n",
    "prompt_template = ChatPromptTemplate.from_template(template_string)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:40:11.488790Z",
     "end_time": "2023-06-13T18:40:11.499436Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": "PromptTemplate(lc_kwargs={'input_variables': ['style', 'text'], 'template': 'Translate the text that is delimited by triple backticks into a style that is {style}. text: ```{text}```\\n'}, input_variables=['style', 'text'], output_parser=None, partial_variables={}, template='Translate the text that is delimited by triple backticks into a style that is {style}. text: ```{text}```\\n', template_format='f-string', validate_template=True)"
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prompt_template.messages[0].prompt"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "从上面的输出可以看出，`prompt_template` 有两个输入变量： `style` 和 `text`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['style', 'text']"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "prompt_template.messages[0].prompt.input_variables"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 3️⃣ 使用模版得到客户消息提示\n",
    "\n",
    "langchain提示模版`prompt_template`需要两个输入变量： `style` 和 `text`。 这里分别对应 \n",
    "- `customer_style`: 我们想要的顾客邮件风格\n",
    "- `customer_email`: 顾客的原始邮件文本。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:40:33.921479Z",
     "end_time": "2023-06-13T18:40:33.926636Z"
    }
   },
   "outputs": [],
   "source": [
    "customer_style = \"\"\"American English \\\n",
    "in a calm and respectful tone\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:40:34.502023Z",
     "end_time": "2023-06-13T18:40:34.511946Z"
    }
   },
   "outputs": [],
   "source": [
    "customer_email = \"\"\"\n",
    "Arrr, I be fuming that me blender lid \\\n",
    "flew off and splattered me kitchen walls \\\n",
    "with smoothie! And to make matters worse, \\\n",
    "the warranty don't cover the cost of \\\n",
    "cleaning up me kitchen. I need yer help \\\n",
    "right now, matey!\n",
    "\"\"\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对于给定的`customer_style`和`customer_email`, 我们可以使用提示模版`prompt_template`的`format_messages`方法生成想要的客户消息`customer_messages`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:40:38.205285Z",
     "end_time": "2023-06-13T18:40:38.214850Z"
    }
   },
   "outputs": [],
   "source": [
    "customer_messages = prompt_template.format_messages(\n",
    "                    style=customer_style,\n",
    "                    text=customer_email)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:40:40.518033Z",
     "end_time": "2023-06-13T18:40:40.534246Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'list'>\n",
      "<class 'langchain.schema.HumanMessage'>\n"
     ]
    }
   ],
   "source": [
    "print(type(customer_messages))\n",
    "print(type(customer_messages[0]))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以看出`customer_messages`变量类型为列表(`list`)，而列表里的元素变量类型为langchain自定义消息(`langchain.schema.HumanMessage`)。\n",
    "\n",
    "打印第一个元素可以得到如下:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:46:57.216766Z",
     "end_time": "2023-06-13T18:46:57.220071Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "lc_kwargs={'content': \"Translate the text that is delimited by triple backticks into a style that is American English in a calm and respectful tone\\n. text: ```\\nArrr, I be fuming that me blender lid flew off and splattered me kitchen walls with smoothie! And to make matters worse, the warranty don't cover the cost of cleaning up me kitchen. I need yer help right now, matey!\\n```\\n\", 'additional_kwargs': {}} content=\"Translate the text that is delimited by triple backticks into a style that is American English in a calm and respectful tone\\n. text: ```\\nArrr, I be fuming that me blender lid flew off and splattered me kitchen walls with smoothie! And to make matters worse, the warranty don't cover the cost of cleaning up me kitchen. I need yer help right now, matey!\\n```\\n\" additional_kwargs={} example=False\n"
     ]
    }
   ],
   "source": [
    "print(customer_messages[0])"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 4️⃣ 调用chat模型转换客户消息风格\n",
    "\n",
    "现在我们可以调用[模型](#model)部分定义的chat模型来实现转换客户消息风格。到目前为止，我们已经实现了在前一部分的任务。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:42:06.183624Z",
     "end_time": "2023-06-13T18:42:08.629599Z"
    }
   },
   "outputs": [],
   "source": [
    "customer_response = chat(customer_messages)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:42:20.689606Z",
     "end_time": "2023-06-13T18:42:20.694279Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I'm really frustrated that my blender lid flew off and made a mess of my kitchen walls with smoothie. To add to my frustration, the warranty doesn't cover the cost of cleaning up my kitchen. Can you please help me out, friend?\n"
     ]
    }
   ],
   "source": [
    "print(customer_response.content)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 5️⃣ 使用模版得到回复消息提示\n",
    "\n",
    "接下来，我们更进一步，将客服人员回复的消息，转换为海盗的语言风格，并确保消息比较有礼貌。 \n",
    "\n",
    "这里，我们可以继续使用第2️⃣步构造的langchain提示模版，来获得我们回复消息提示。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:47:07.261601Z",
     "end_time": "2023-06-13T18:47:07.271685Z"
    }
   },
   "outputs": [],
   "source": [
    "service_reply = \"\"\"Hey there customer, \\\n",
    "the warranty does not cover \\\n",
    "cleaning expenses for your kitchen \\\n",
    "because it's your fault that \\\n",
    "you misused your blender \\\n",
    "by forgetting to put the lid on before \\\n",
    "starting the blender. \\\n",
    "Tough luck! See ya!\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:47:07.848670Z",
     "end_time": "2023-06-13T18:47:07.853878Z"
    }
   },
   "outputs": [],
   "source": [
    "service_style_pirate = \"\"\"\\\n",
    "a polite tone \\\n",
    "that speaks in English Pirate\\\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:47:21.057130Z",
     "end_time": "2023-06-13T18:47:21.062844Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "lc_kwargs={'content': \"Translate the text that is delimited by triple backticks into a style that is a polite tone that speaks in English Pirate. text: ```Hey there customer, the warranty does not cover cleaning expenses for your kitchen because it's your fault that you misused your blender by forgetting to put the lid on before starting the blender. Tough luck! See ya!\\n```\\n\", 'additional_kwargs': {}} content=\"Translate the text that is delimited by triple backticks into a style that is a polite tone that speaks in English Pirate. text: ```Hey there customer, the warranty does not cover cleaning expenses for your kitchen because it's your fault that you misused your blender by forgetting to put the lid on before starting the blender. Tough luck! See ya!\\n```\\n\" additional_kwargs={} example=False\n"
     ]
    }
   ],
   "source": [
    "service_messages = prompt_template.format_messages(\n",
    "    style=service_style_pirate,\n",
    "    text=service_reply)\n",
    "\n",
    "print(service_messages[0].content)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 6️⃣ 调用chat模型转换回复消息风格\n",
    "\n",
    "调用[模型](#model)部分定义的chat模型来转换回复消息风格"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {
    "tags": [],
    "ExecuteTime": {
     "start_time": "2023-06-13T18:47:33.835642Z",
     "end_time": "2023-06-13T18:47:38.180380Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ahoy there, matey! I must kindly inform ye that the warranty be not coverin' the expenses o' cleaning yer galley, as 'tis yer own fault fer misusin' yer blender by forgettin' to put the lid on afore startin' it. Aye, tough luck! Farewell and may the winds be in yer favor!\n"
     ]
    }
   ],
   "source": [
    "service_response = chat(service_messages)\n",
    "print(service_response.content)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "#### ❓为什么需要提示模版\n",
    "\n",
    "\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "在应用于比较复杂的场景时，提示可能会非常长并且包含涉及许多细节。使用提示模版，可以让我们更为方便地重复使用设计好的提示。\n",
    "\n",
    "下面给出了一个比较长的提示模版案例。学生们线上学习并提交作业，通过以下的提示来实现对学生的提交的作业的评分。\n",
    "\n",
    "```python\n",
    "    prompt = \"\"\" Your task is to determine if the student's solution is correct or not\n",
    "\n",
    "    To solve the problem do the following:\n",
    "    - First, workout your own solution to the problem\n",
    "    - Then compare your solution to the student's solution \n",
    "    and evaluate if the sudtent's solution is correct or not.\n",
    "    ...\n",
    "    Use the following format:\n",
    "    Question:\n",
    "    ```\n",
    "    question here\n",
    "    ```\n",
    "    Student's solution:\n",
    "    ```\n",
    "    student's solution here\n",
    "    ```\n",
    "    Actual solution:\n",
    "    ```\n",
    "    ...\n",
    "    steps to work out the solution and your solution here\n",
    "    ```\n",
    "    Is the student's solution the same as acutal solution \\\n",
    "    just calculated:\n",
    "    ```\n",
    "    yes or no\n",
    "    ```\n",
    "    Student grade\n",
    "    ```\n",
    "    correct or incorrect\n",
    "    ```\n",
    "    \n",
    "    Question:\n",
    "    ```\n",
    "    {question}\n",
    "    ```\n",
    "    Student's solution:\n",
    "    ```\n",
    "    {student's solution}\n",
    "    ```\n",
    "    Actual solution:\n",
    "    \n",
    "    \"\"\"\n",
    "```\n",
    "\n",
    "此外，LangChain还提供了提示模版用于一些常用场景。比如summarization, Question answering, or connect to sql databases, or connect to different APIs. 通过使用LongChain内置的提示模版，你可以快速建立自己的大模型应用，而不需要花时间去设计和构造提示。\n",
    "\n",
    "最后，我们在建立大模型应用时，通常希望模型的输出为给定的格式，比如在输出使用特定的关键词来让输出结构化。 下面为一个使用大模型进行链式思考推理例子，对于问题：`What is the elevation range for the area that the eastern sector of the Colorado orogeny extends into?`, 通过使用LangChain库函数，输出采用\"Thought\"（思考）、\"Action\"（行动）、\"Observation\"（观察）作为链式思考推理的关键词，让输出结构化。在[补充材料](#reason_act)中，可以查看使用LangChain和OpenAI进行链式思考推理的另一个代码实例。\n",
    "\n",
    "```python\n",
    "\"\"\"\n",
    "Thought: I need to search Colorado orogeny, find the area that the eastern sector of the Colorado orogeny extends into, then find the elevation range of the area.\n",
    "Action: Search[Colorado orogeny]\n",
    "Observation: The Colorado orogeny was an episode of mountain building (an orogeny) in Colorado and surrounding areas.\n",
    "\n",
    "Thought: It does not mention the eastern sector. So I need to look up eastern sector.\n",
    "Action: Lookup[eastern sector]\n",
    "Observation: (Result 1 / 1) The eastern sector extends into the High Plains and is called the Central Plains orogeny.\n",
    "\n",
    "Thought: The eastern sector of Colorado orogeny extends into the High Plains. So I need to search High Plains and find its elevation range.\n",
    "Action: Search[High Plains]\n",
    "Observation: High Plains refers to one of two distinct land regions\n",
    "\n",
    "Thought: I need to instead search High Plains (United States).\n",
    "Action: Search[High Plains (United States)]\n",
    "Observation: The High Plains are a subregion of the Great Plains. From east to west, the High Plains rise in elevation from around 1,800 to 7,000 ft (550 to 2,130 m).[3]\n",
    "\n",
    "Thought: High Plains rise in elevation from around 1,800 to 7,000 ft, so the answer is 1,800 to 7,000 ft.\n",
    "Action: Finish[1,800 to 7,000 ft]\n",
    "\n",
    "\"\"\"\n",
    "```\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 输出解析器"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 📚 如果没有输出解析器\n",
    "\n",
    "对于给定的评价`customer_review`, 我们希望提取信息，并按以下格式输出：\n",
    "\n",
    "```python\n",
    "{\n",
    "  \"gift\": False,\n",
    "  \"delivery_days\": 5,\n",
    "  \"price_value\": \"pretty affordable!\"\n",
    "}\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2023-06-13T19:01:11.236714Z",
     "end_time": "2023-06-13T19:01:11.256924Z"
    }
   },
   "outputs": [],
   "source": [
    "customer_review = \"\"\"\\\n",
    "This leaf blower is pretty amazing.  It has four settings:\\\n",
    "candle blower, gentle breeze, windy city, and tornado. \\\n",
    "It arrived in two days, just in time for my wife's \\\n",
    "anniversary present. \\\n",
    "I think my wife liked it so much she was speechless. \\\n",
    "So far I've been the only one using it, and I've been \\\n",
    "using it every other morning to clear the leaves on our lawn. \\\n",
    "It's slightly more expensive than the other leaf blowers \\\n",
    "out there, but I think it's worth it for the extra features.\n",
    "\"\"\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 1️⃣ 构造提示模版字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2023-06-13T19:00:46.697309Z",
     "end_time": "2023-06-13T19:00:46.709114Z"
    }
   },
   "outputs": [],
   "source": [
    "review_template = \"\"\"\\\n",
    "For the following text, extract the following information:\n",
    "\n",
    "gift: Was the item purchased as a gift for someone else? \\\n",
    "Answer True if yes, False if not or unknown.\n",
    "\n",
    "delivery_days: How many days did it take for the product \\\n",
    "to arrive? If this information is not found, output -1.\n",
    "\n",
    "price_value: Extract any sentences about the value or price,\\\n",
    "and output them as a comma separated Python list.\n",
    "\n",
    "Format the output as JSON with the following keys:\n",
    "gift\n",
    "delivery_days\n",
    "price_value\n",
    "\n",
    "text: {text}\n",
    "\"\"\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 2️⃣ 构造langchain提示模版"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2023-06-13T19:01:06.393439Z",
     "end_time": "2023-06-13T19:01:06.393963Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "lc_kwargs={'input_variables': ['text'], 'messages': [HumanMessagePromptTemplate(lc_kwargs={'prompt': PromptTemplate(lc_kwargs={'input_variables': ['text'], 'template': 'For the following text, extract the following information:\\n\\ngift: Was the item purchased as a gift for someone else? Answer True if yes, False if not or unknown.\\n\\ndelivery_days: How many days did it take for the product to arrive? If this information is not found, output -1.\\n\\nprice_value: Extract any sentences about the value or price,and output them as a comma separated Python list.\\n\\nFormat the output as JSON with the following keys:\\ngift\\ndelivery_days\\nprice_value\\n\\ntext: {text}\\n'}, input_variables=['text'], output_parser=None, partial_variables={}, template='For the following text, extract the following information:\\n\\ngift: Was the item purchased as a gift for someone else? Answer True if yes, False if not or unknown.\\n\\ndelivery_days: How many days did it take for the product to arrive? If this information is not found, output -1.\\n\\nprice_value: Extract any sentences about the value or price,and output them as a comma separated Python list.\\n\\nFormat the output as JSON with the following keys:\\ngift\\ndelivery_days\\nprice_value\\n\\ntext: {text}\\n', template_format='f-string', validate_template=True)}, prompt=PromptTemplate(lc_kwargs={'input_variables': ['text'], 'template': 'For the following text, extract the following information:\\n\\ngift: Was the item purchased as a gift for someone else? Answer True if yes, False if not or unknown.\\n\\ndelivery_days: How many days did it take for the product to arrive? If this information is not found, output -1.\\n\\nprice_value: Extract any sentences about the value or price,and output them as a comma separated Python list.\\n\\nFormat the output as JSON with the following keys:\\ngift\\ndelivery_days\\nprice_value\\n\\ntext: {text}\\n'}, input_variables=['text'], output_parser=None, partial_variables={}, template='For the following text, extract the following information:\\n\\ngift: Was the item purchased as a gift for someone else? Answer True if yes, False if not or unknown.\\n\\ndelivery_days: How many days did it take for the product to arrive? If this information is not found, output -1.\\n\\nprice_value: Extract any sentences about the value or price,and output them as a comma separated Python list.\\n\\nFormat the output as JSON with the following keys:\\ngift\\ndelivery_days\\nprice_value\\n\\ntext: {text}\\n', template_format='f-string', validate_template=True), additional_kwargs={})]} input_variables=['text'] output_parser=None partial_variables={} messages=[HumanMessagePromptTemplate(lc_kwargs={'prompt': PromptTemplate(lc_kwargs={'input_variables': ['text'], 'template': 'For the following text, extract the following information:\\n\\ngift: Was the item purchased as a gift for someone else? Answer True if yes, False if not or unknown.\\n\\ndelivery_days: How many days did it take for the product to arrive? If this information is not found, output -1.\\n\\nprice_value: Extract any sentences about the value or price,and output them as a comma separated Python list.\\n\\nFormat the output as JSON with the following keys:\\ngift\\ndelivery_days\\nprice_value\\n\\ntext: {text}\\n'}, input_variables=['text'], output_parser=None, partial_variables={}, template='For the following text, extract the following information:\\n\\ngift: Was the item purchased as a gift for someone else? Answer True if yes, False if not or unknown.\\n\\ndelivery_days: How many days did it take for the product to arrive? If this information is not found, output -1.\\n\\nprice_value: Extract any sentences about the value or price,and output them as a comma separated Python list.\\n\\nFormat the output as JSON with the following keys:\\ngift\\ndelivery_days\\nprice_value\\n\\ntext: {text}\\n', template_format='f-string', validate_template=True)}, prompt=PromptTemplate(lc_kwargs={'input_variables': ['text'], 'template': 'For the following text, extract the following information:\\n\\ngift: Was the item purchased as a gift for someone else? Answer True if yes, False if not or unknown.\\n\\ndelivery_days: How many days did it take for the product to arrive? If this information is not found, output -1.\\n\\nprice_value: Extract any sentences about the value or price,and output them as a comma separated Python list.\\n\\nFormat the output as JSON with the following keys:\\ngift\\ndelivery_days\\nprice_value\\n\\ntext: {text}\\n'}, input_variables=['text'], output_parser=None, partial_variables={}, template='For the following text, extract the following information:\\n\\ngift: Was the item purchased as a gift for someone else? Answer True if yes, False if not or unknown.\\n\\ndelivery_days: How many days did it take for the product to arrive? If this information is not found, output -1.\\n\\nprice_value: Extract any sentences about the value or price,and output them as a comma separated Python list.\\n\\nFormat the output as JSON with the following keys:\\ngift\\ndelivery_days\\nprice_value\\n\\ntext: {text}\\n', template_format='f-string', validate_template=True), additional_kwargs={})]\n"
     ]
    }
   ],
   "source": [
    "from langchain.prompts import ChatPromptTemplate\n",
    "prompt_template = ChatPromptTemplate.from_template(review_template)\n",
    "print(prompt_template)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 3️⃣ 使用模版得到提示消息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2023-06-13T19:05:54.391540Z",
     "end_time": "2023-06-13T19:05:54.398371Z"
    }
   },
   "outputs": [],
   "source": [
    "messages = prompt_template.format_messages(text=customer_review)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 4️⃣ 调用chat模型提取信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2023-06-13T19:05:56.719051Z",
     "end_time": "2023-06-13T19:06:00.187024Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "    \"gift\": true,\n",
      "    \"delivery_days\": 2,\n",
      "    \"price_value\": [\"It's slightly more expensive than the other leaf blowers out there, but I think it's worth it for the extra features.\"]\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "chat = ChatOpenAI(temperature=0.0)\n",
    "response = chat(messages)\n",
    "print(response.content)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 📝 分析与总结\n",
    "`response.content`类型为字符串（`str`），而并非字典(`dict`), 直接使用`get`方法会报错。因此，我们需要输出解释器。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "str"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(response.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'str' object has no attribute 'get'",
     "output_type": "error",
     "traceback": [
      "\u001B[0;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[0;31mAttributeError\u001B[0m                            Traceback (most recent call last)",
      "Cell \u001B[0;32mIn[48], line 1\u001B[0m\n\u001B[0;32m----> 1\u001B[0m \u001B[43mresponse\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mcontent\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mget\u001B[49m(\u001B[38;5;124m'\u001B[39m\u001B[38;5;124mgift\u001B[39m\u001B[38;5;124m'\u001B[39m)\n",
      "\u001B[0;31mAttributeError\u001B[0m: 'str' object has no attribute 'get'"
     ]
    }
   ],
   "source": [
    "response.content.get('gift')"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 📚 LangChain输出解析器"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 1️⃣ 构造提示模版字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2023-06-13T19:06:07.253908Z",
     "end_time": "2023-06-13T19:06:07.266834Z"
    }
   },
   "outputs": [],
   "source": [
    "review_template_2 = \"\"\"\\\n",
    "For the following text, extract the following information:\n",
    "\n",
    "gift: Was the item purchased as a gift for someone else? \\\n",
    "Answer True if yes, False if not or unknown.\n",
    "\n",
    "delivery_days: How many days did it take for the product\\\n",
    "to arrive? If this information is not found, output -1.\n",
    "\n",
    "price_value: Extract any sentences about the value or price,\\\n",
    "and output them as a comma separated Python list.\n",
    "\n",
    "text: {text}\n",
    "\n",
    "{format_instructions}\n",
    "\"\"\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 2️⃣ 构造langchain提示模版"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2023-06-13T19:06:09.335158Z",
     "end_time": "2023-06-13T19:06:09.353325Z"
    }
   },
   "outputs": [],
   "source": [
    "prompt = ChatPromptTemplate.from_template(template=review_template_2)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 🔥 构造输出解析器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2023-06-13T19:06:38.889817Z",
     "end_time": "2023-06-13T19:06:38.895223Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The output should be a markdown code snippet formatted in the following schema, including the leading and trailing \"```json\" and \"```\":\n",
      "\n",
      "```json\n",
      "{\n",
      "\t\"gift\": string  // Was the item purchased                             as a gift for someone else?                              Answer True if yes,                             False if not or unknown.\n",
      "\t\"delivery_days\": string  // How many days                                      did it take for the product                                      to arrive? If this                                       information is not found,                                      output -1.\n",
      "\t\"price_value\": string  // Extract any                                    sentences about the value or                                     price, and output them as a                                     comma separated Python list.\n",
      "}\n",
      "```\n"
     ]
    }
   ],
   "source": [
    "from langchain.output_parsers import ResponseSchema\n",
    "from langchain.output_parsers import StructuredOutputParser\n",
    "\n",
    "gift_schema = ResponseSchema(name=\"gift\",\n",
    "                             description=\"Was the item purchased\\\n",
    "                             as a gift for someone else? \\\n",
    "                             Answer True if yes,\\\n",
    "                             False if not or unknown.\")\n",
    "\n",
    "delivery_days_schema = ResponseSchema(name=\"delivery_days\",\n",
    "                                      description=\"How many days\\\n",
    "                                      did it take for the product\\\n",
    "                                      to arrive? If this \\\n",
    "                                      information is not found,\\\n",
    "                                      output -1.\")\n",
    "\n",
    "price_value_schema = ResponseSchema(name=\"price_value\",\n",
    "                                    description=\"Extract any\\\n",
    "                                    sentences about the value or \\\n",
    "                                    price, and output them as a \\\n",
    "                                    comma separated Python list.\")\n",
    "\n",
    "response_schemas = [gift_schema, \n",
    "                    delivery_days_schema,\n",
    "                    price_value_schema]\n",
    "output_parser = StructuredOutputParser.from_response_schemas(response_schemas)\n",
    "format_instructions = output_parser.get_format_instructions()\n",
    "print(format_instructions)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 3️⃣ 使用模版得到提示消息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2023-06-13T19:07:16.737211Z",
     "end_time": "2023-06-13T19:07:16.743368Z"
    }
   },
   "outputs": [],
   "source": [
    "messages = prompt.format_messages(text=customer_review, format_instructions=format_instructions)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2023-06-13T19:07:17.869106Z",
     "end_time": "2023-06-13T19:07:17.883179Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "For the following text, extract the following information:\n",
      "\n",
      "gift: Was the item purchased as a gift for someone else? Answer True if yes, False if not or unknown.\n",
      "\n",
      "delivery_days: How many days did it take for the productto arrive? If this information is not found, output -1.\n",
      "\n",
      "price_value: Extract any sentences about the value or price,and output them as a comma separated Python list.\n",
      "\n",
      "text: This leaf blower is pretty amazing.  It has four settings:candle blower, gentle breeze, windy city, and tornado. It arrived in two days, just in time for my wife's anniversary present. I think my wife liked it so much she was speechless. So far I've been the only one using it, and I've been using it every other morning to clear the leaves on our lawn. It's slightly more expensive than the other leaf blowers out there, but I think it's worth it for the extra features.\n",
      "\n",
      "\n",
      "The output should be a markdown code snippet formatted in the following schema, including the leading and trailing \"```json\" and \"```\":\n",
      "\n",
      "```json\n",
      "{\n",
      "\t\"gift\": string  // Was the item purchased                             as a gift for someone else?                              Answer True if yes,                             False if not or unknown.\n",
      "\t\"delivery_days\": string  // How many days                                      did it take for the product                                      to arrive? If this                                       information is not found,                                      output -1.\n",
      "\t\"price_value\": string  // Extract any                                    sentences about the value or                                     price, and output them as a                                     comma separated Python list.\n",
      "}\n",
      "```\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(messages[0].content)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 4️⃣ 调用chat模型提取信息"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2023-06-13T19:07:42.792090Z",
     "end_time": "2023-06-13T19:07:45.870688Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "```json\n",
      "{\n",
      "\t\"gift\": true,\n",
      "\t\"delivery_days\": \"2\",\n",
      "\t\"price_value\": [\"It's slightly more expensive than the other leaf blowers out there, but I think it's worth it for the extra features.\"]\n",
      "}\n",
      "```\n"
     ]
    }
   ],
   "source": [
    "response = chat(messages)\n",
    "print(response.content)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 5️⃣ 使用输出解析器解析输出"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2023-06-13T19:07:50.413248Z",
     "end_time": "2023-06-13T19:07:50.430386Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": "{'gift': True,\n 'delivery_days': '2',\n 'price_value': [\"It's slightly more expensive than the other leaf blowers out there, but I think it's worth it for the extra features.\"]}"
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "output_dict = output_parser.parse(response.content)\n",
    "output_dict"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 📝 分析与总结\n",
    "`output_dict`类型为字典(`dict`), 可直接使用`get`方法。这样的输出更方便下游任务的处理。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(output_dict)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'2'"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "output_dict.get('delivery_days')"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 补充材料"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 链式思考推理(ReAct) <a id='reason_act'></a>\n",
    "参考资料：[ReAct (Reason+Act) prompting in OpenAI GPT and LangChain](https://tsmatz.wordpress.com/2023/03/07/react-with-openai-gpt-and-langchain/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install -q wikipedia"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {
    "ExecuteTime": {
     "start_time": "2023-06-13T19:17:34.052097Z",
     "end_time": "2023-06-13T19:17:58.719306Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/langchain/llms/openai.py:179: UserWarning: You are trying to use a chat model. This way of initializing it is no longer supported. Instead, please use: `from langchain.chat_models import ChatOpenAI`\n",
      "  warnings.warn(\n",
      "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/langchain/llms/openai.py:751: UserWarning: You are trying to use a chat model. This way of initializing it is no longer supported. Instead, please use: `from langchain.chat_models import ChatOpenAI`\n",
      "  warnings.warn(\n",
      "Error in on_chain_start callback: 'name'\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001B[32;1m\u001B[1;3mThought: I need to search David Chanoff and find the U.S. Navy admiral he collaborated with, then find out which President the admiral served as the ambassador to the United Kingdom under.\n",
      "Action: Search[David Chanoff]\u001B[0m\n",
      "Observation: \u001B[36;1m\u001B[1;3mDavid Chanoff is a noted author of non-fiction work. His work has typically involved collaborations with the principal protagonist of the work concerned. His collaborators have included; Augustus A. White, Joycelyn Elders, Đoàn Văn Toại, William J. Crowe, Ariel Sharon, Kenneth Good and Felix Zandman. He has also written about a wide range of subjects including literary history, education and foreign for The Washington Post, The New Republic and The New York Times Magazine. He has published more than twelve books.\u001B[0m\n",
      "Thought:\u001B[32;1m\u001B[1;3mDavid Chanoff has collaborated with William J. Crowe. I need to find out which President William J. Crowe served as the ambassador to the United Kingdom under.\n",
      "Action: Search[William J. Crowe]\u001B[0m\n",
      "Observation: \u001B[36;1m\u001B[1;3mWilliam James Crowe Jr. (January 2, 1925 – October 18, 2007) was a United States Navy admiral and diplomat who served as the 11th chairman of the Joint Chiefs of Staff under Presidents Ronald Reagan and George H. W. Bush, and as the ambassador to the United Kingdom and Chair of the Intelligence Oversight Board under President Bill Clinton.\u001B[0m\n",
      "Thought:\u001B[32;1m\u001B[1;3mWilliam J. Crowe served as the ambassador to the United Kingdom under President Bill Clinton. So the answer is Bill Clinton. \n",
      "Action: Finish[Bill Clinton]\u001B[0m\n",
      "\n",
      "\u001B[1m> Finished chain.\u001B[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": "'Bill Clinton'"
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain.docstore.wikipedia import Wikipedia\n",
    "from langchain.llms import OpenAI\n",
    "from langchain.agents import initialize_agent, Tool, AgentExecutor\n",
    "from langchain.agents.react.base import DocstoreExplorer\n",
    "\n",
    "docstore=DocstoreExplorer(Wikipedia())\n",
    "tools = [\n",
    "  Tool(\n",
    "    name=\"Search\",\n",
    "    func=docstore.search,\n",
    "    description=\"Search for a term in the docstore.\",\n",
    "  ),\n",
    "  Tool(\n",
    "    name=\"Lookup\",\n",
    "    func=docstore.lookup,\n",
    "    description=\"Lookup a term in the docstore.\",\n",
    "  )\n",
    "]\n",
    "\n",
    "# 使用大语言模型\n",
    "llm = OpenAI(\n",
    "  model_name=\"gpt-3.5-turbo\",\n",
    "  temperature=0,\n",
    ")\n",
    "\n",
    "# 初始化ReAct代理\n",
    "react = initialize_agent(tools, llm, agent=\"react-docstore\", verbose=True)\n",
    "agent_executor = AgentExecutor.from_agent_and_tools(\n",
    "  agent=react.agent,\n",
    "  tools=tools,\n",
    "  verbose=True,\n",
    ")\n",
    "\n",
    "\n",
    "question = \"Author David Chanoff has collaborated with a U.S. Navy admiral who served as the ambassador to the United Kingdom under which President?\"\n",
    "agent_executor.run(question)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [],
   "metadata": {
    "collapsed": false
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
